<template>
	<view class="comment-section" ref="commentRef" @scroll="handleScroll">
		<!-- 分割线：wd-divider → up-divider（属性完全兼容） -->
		<!-- <up-divider color="#4D80F0"></up-divider> -->

		<!-- 评论标题（无组件，样式不变） -->
		<view class="comment-header">
			<text class="comment-title">评论区</text>
			<text class="comment-count">({{ commentCount || 0 }})</text>
		</view>

		<!-- 评论加载中：wd-loading → up-loading -->
		<view class="comment-loading" v-if="commentLoading && page === 1">
			<up-loading-icon size="small" color="#4D80F0" />
			<text class="loading-text">加载评论中...</text>
		</view>

		<!-- 一级评论列表 -->
		<view class="comment-list" v-else-if="firstLevelComments.length">
			<view class="comment-item" v-for="comment in firstLevelComments" :key="comment.commentId" @click="handleCommentClick(comment)">
				<!-- 评论头像：wd-img → up-image（关键适配） -->
				<up-image :src="comment.senderAvatar || props.defaultAvatar" width="100rpx" height="100rpx"></up-image>

				<!-- 评论内容区（无组件，样式不变） -->
				<view class="comment-content-wrap">
					<view class="comment-header-row">
						<text class="commentor-name" @click="onClickUser(comment.userId)">{{ comment.sender || '匿名用户' }}</text>
						<text class="comment-time">{{ props.formatTime(comment.createTime) }}</text>
					</view>

					<text class="comment-desc">{{ comment.content || '无评论内容' }}</text>

					<!-- 二级回复列表（折叠/展开） -->
					<view class="reply-list" v-if="comment.replies && comment.replies.length">
						<view class="comment-item reply-item" v-for="(reply, idx) in getShowReplies(comment)" :key="reply.commentId" @click.stop="handleReplyClick(reply, comment)">
							<!-- 回复头像：wd-img → up-image -->
							<up-image  :src="reply.senderAvatar || 'https://picsum.photos/200/200?random=6'" width="100rpx" height="100rpx"></up-image>
							<view class="comment-content-wrap">
								<view class="comment-header-row">
									<text class="commentor-name" @click="onClickUser(comment.replyUserId)">{{ reply.sender || '匿名用户' }}</text>
									<text class="comment-time">{{ props.formatTime(reply.createTime) }}</text>
								</view>
								<text class="comment-desc">
									<text class="reply-at" v-if="reply.receiver">@{{ reply.receiver }}：</text>
									{{ reply.content }}
								</text>
							</view>
						</view>

						<!-- 展开/收起按钮（无组件，样式不变） -->
						<view class="reply-toggle" @click.stop="toggleReply(comment.commentId)">
							<text class="toggle-text">
								{{ showAllReplies[comment.commentId] ? '收起' : `查看${comment.replies.length - 2}条回复` }}
							</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多提示：wd-loading → up-loading -->
			<view class="load-more" v-if="commentLoading && page > 1">
				<up-loading-icon size="small" color="#4D80F0" />
				<text class="load-more-text">加载更多评论...</text>
			</view>
			<view class="no-more" v-if="!hasMore && !commentLoading && firstLevelComments.length > 0">
				<text class="no-more-text">没有更多评论了</text>
			</view>
		</view>

		<!-- 空评论状态：wd-img → up-image -->
		<view class="empty-comment" v-else-if="!commentLoading">
			<text class="empty-text">暂无评论，快来抢沙发～</text>
		</view>

		<!-- 底部固定输入框：wd-input → up-input；wd-button → up-button -->
		<view class="comment-input-area">
			<up-input
				ref="commentInput"
				v-model="inputValue"
				:placeholder="replyTarget ? `回复 @${replyTarget.sender}` : '说点什么...'"
				class="input"
				maxlength="200"
				@focus="handleInputFocus"
			></up-input>
<!-- 			字数统计（无组件，样式不变）
			<text class="word-count">{{ inputValue.length }}/200</text> -->
			<!-- 发送按钮：wd-button → up-button -->
			<up-button class="send-btn" type="primary" size="mini" @click="handleSubmit" :disabled="!inputValue.trim()">发送</up-button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 接收父组件参数（完全保留，无修改）
const props = defineProps({
	comments: { type: Array, default: () => [] },
	commentCount: { type: Number, default: 0 },
	defaultAvatar: { type: String, default: 'https://picsum.photos/200/200?random=1' },
	formatTime: { type: Function, required: true },
	currentUser: { type: Object, default: () => ({}) },
	page: { type: Number, default: 1 },
	pageSize: { type: Number, default: 10 },
	hasMore: { type: Boolean, default: true },
	commentLoading: { type: Boolean, default: false }
});

// 向父组件触发事件（完全保留，无修改）
const emit = defineEmits(['submitComment', 'submitReply', 'load-more', 'click-user']);

// 核心状态管理（完全保留，无修改）
const commentRef = ref(null);
const commentInput = ref(null);

const inputValue = ref('');
const replyTarget = ref(null);
const showAllReplies = ref({});

// 计算一级评论（含关联的二级回复）（完全保留，无修改）
const firstLevelComments = computed(() => {
	return props.comments
		.filter((comment) => comment.parentId === 0)
		.map((comment) => ({
			...comment,
			replies: props.comments.filter((reply) => reply.parentId === comment.commentId) || []
		}));
});

// 计算当前显示的回复（默认2条，展开显示全部）（完全保留，无修改）
const getShowReplies = (comment) => {
	if (!comment.replies) return [];
	return showAllReplies.value[comment.commentId] ? comment.replies : comment.replies.slice(0, 2);
};

// 点击一级评论触发回复（完全保留，无修改）
const handleCommentClick = (comment) => {
	if (event && event.target.closest('.reply-toggle')) {
		return;
	}

	replyTarget.value = {
		commentId: comment.commentId,
		sender: comment.sender,
		parentId: comment.commentId
	};

	inputValue.value = `@${comment.sender} `;
	setTimeout(() => commentInput.value?.focus(), 100);
};

// 点击回复触发回复功能（完全保留，无修改）
const handleReplyClick = (target, parentComment) => {
	replyTarget.value = {
		commentId: target.commentId,
		sender: target.sender,
		parentId: parentComment.commentId
	};

	inputValue.value = `@${target.sender} `;
	setTimeout(() => commentInput.value?.focus(), 100);
};

// 切换回复展开/收起（完全保留，无修改）
const toggleReply = (commentId) => {
	showAllReplies.value[commentId] = !showAllReplies.value[commentId];
};

// 提交评论/回复（完全保留，无修改）
const handleSubmit = () => {
	// console.log(commentInput.value);
	const content = inputValue.value.trim();
	if (!content) return;

	if (replyTarget.value) {
		const pureContent = content.replace(`@${replyTarget.value.sender} `, '');
		emit('submitReply', {
			content: pureContent,
			parentId: replyTarget.value.parentId,
			targetNickname: replyTarget.value.sender
		});
	} else {
		emit('submitComment', { content });
	}

	inputValue.value = '';
	replyTarget.value = null;
};

// 滚动到底部加载更多（完全保留，无修改）
const handleScroll = () => {
	const el = commentRef.value;
	if (!el) return;

	const scrollBottom = el.scrollTop + el.clientHeight + 100;
	if (scrollBottom >= el.scrollHeight && props.hasMore && !props.commentLoading) {
		emit('load-more');
	}
};

// 传递点击用户ID（完全保留，无修改）
const onClickUser = (userId) => {
	if (!userId) return;
	emit('click-user', userId);
};

// 暴露给父组件的方法（完全保留，无修改）
defineExpose({
	scrollToComment() {
		commentRef.value && commentRef.value.scrollIntoView({ behavior: 'smooth' });
		setTimeout(() => commentInput.value?.focus(), 300);
	},
	focusInput() {
		commentInput.value?.focus();
	}
});

// 输入框聚焦时滚动到底部（完全保留，无修改）
const handleInputFocus = () => {
	commentRef.value && (commentRef.value.scrollTop = commentRef.value.scrollHeight);
};
</script>

<style lang="scss" scoped>
@import './styles/comment-section.scss';
</style>
